package com.rocbrid.controller;


import com.rocbrid.common.R;
import com.rocbrid.utils.CosUploader;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {

    /**
     * 本地上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploads")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        //获取到类路径
        String currentDir = System.getProperty("user.dir");
        UUID uuid = UUID.randomUUID();
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //  file.transferTo(new File("classpath:"+uuid+originalFilename));
        file.transferTo(new File(currentDir+uuid+substring));
        return R.ok();
    }

    /**
     * 使用腾讯云oss上传
     * @param file
     * @return
     */

    @PostMapping("/upload")
    public String handleUpload(@RequestParam("file") MultipartFile file) {
        try {
            String imageUrl = CosUploader.uploadImage(file);
            return "上传成功！访问地址：" + imageUrl;
        } catch (Exception e) {
            return "上传失败：" + e.getMessage();
        }
    }
}
